import Vue from "vue";
import VueRouter from "vue-router";
import Home from "../views/Home.vue";

import store from "../store";

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    redirect: "/home",
  },
  {
    path: "/home",
    props: true,
    name: "Home",
    component: Home,
  },
  {
    path: "/about",
    name: "About",
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () =>
      import(/* webpackChunkName: "about" */ "../views/About.vue"),
  },
  {
    path: "/manage",
    component: () =>
      import(/* webpackChunkName: "manage" */ "../views/Manage.vue"),
  },
  {
    path: "/404",
    component: () => import(/* webpackChunkName: "404" */ "../views/404.vue"),
  },
  {
    path: "*",
    redirect: "/404",
    // component: () => import(/* webpackChunkName: "about" */ "../views/404.vue"),
  },
];

const router = new VueRouter({
  routes,
});

export default router;

function findPathInMenu(path, menu) {
  if (menu.link === path) {
    return true;
  }

  return (
    (menu.children || []).find((child) => findPathInMenu(path, child)) !==
    undefined
  );
}

router.beforeEach((to, from, next) => {
  const path = to.path;
  if (path === "/404") {
    next();
    return;
  }

  const app = router.app;

  return Promise.resolve(
    store.state.menusLoaded
      ? store.state.menus
      : new Promise((resolve) => {
          app._watchers = [];
          app.$watch("$store.state.menusLoaded", () => {
            resolve(store.state.menus);
          });
        })
  ).then((menus) => {
    if (findPathInMenu(path, { children: menus })) {
      next();
    } else {
      next({ path: "/404" });
    }
  });
});
